import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex)

export default new Vuex.Store({
  //一个对象，包含了应用中全部的应用层级状态数据
  state: {
    user: JSON.parse(sessionStorage.getItem("user")),
    token: sessionStorage.getItem("token"),
  },
  getters: {},
  mutations: {
    //可以通过:$store.commit('updateUser')
    updateUser(state, payload) {
      state.user = payload
      sessionStorage.setItem("user", JSON.stringify(payload))
    },
    //用户保存token
    saveToken(state, token) {
      state.token = token
      sessionStorage.setItem("token", token)
    },
  },
  actions: {
    //先发异步请求，获取登录用户,更新state
    //可以通过:$store.dispatch('loginAndSaveUser',{...})
    loginAndSaveUser(store, payload) {
      store.commit("updateUser", { nickname: "测试用户" })
    },
  },
  modules: {},
})
